import tensorflow as tf

list = ["./test.PNG", "./test.PNG", "./test.PNG", "./test.PNG"
    , "./test.PNG", "./test.PNG", "./test.PNG", "./test.PNG"]

G_W = 28
G_H = 28
G_C = 1


def decode_from_file(file, height, width, channel):
    image_contents = tf.read_file(file)
    image = tf.image.decode_jpeg(image_contents, channels=channel)
    image = tf.image.resize_image_with_crop_or_pad(image, height, width)
    image = tf.image.per_image_standardization(image)
    return image


def path_list_to_img_batch(path_list, width, height, channel):
    '''
    :param path_list: example : filenames_placeholder = tf.placeholder(tf.string, [None, ])
    :return: batch of images shape ( batch size, W ,H ,C )
    '''
    batch_size = tf.shape(path_list)[0]
    first_image = decode_from_file(path_list[0], height, width, channel)
    first_image = tf.expand_dims(first_image, 0)
    c = lambda i, batch_im: i < batch_size

    def body(i, batch_im):
        cur_file = path_list[i]
        image = decode_from_file(cur_file, height, width, channel)
        image = tf.expand_dims(image, 0)
        batch_im = tf.concat([image, batch_im], 0)
        # i = tf.Print(i,
        #              ["I:", i, " file:", cur_file, "image:", tf.shape(image), " batch shape:", tf.shape(batch_im)])
        return (i + 1, batch_im)

    i0 = tf.constant(1)
    i_out, im_batch_out = tf.while_loop(c, body, [i0, first_image],
                                        shape_invariants=[i0.get_shape(),
                                                          tf.TensorShape([None, width, height, channel])]
                                        )
    # im_batch_out = tf.Print(im_batch_out, ["batch shape:", tf.shape(im_batch_out)])
    return im_batch_out


def case_test():
    graph = tf.Graph()
    with graph.as_default():
        filenames_placeholder = tf.placeholder(tf.string, [None, ])
        im_batch = path_list_to_img_batch(filenames_placeholder, G_W, G_H, G_C)
        # im_batch = tf.Print(im_batch, ["batch shape:", tf.shape(im_batch)])

    with tf.Session(graph=graph) as sess:
        #  as sess.run input is a list , output will be a list as well
        img_batch_ = sess.run(im_batch, feed_dict={filenames_placeholder: list})
        print("batch shape:{}".format(img_batch_.shape))

# case_test()
